package com.example.score;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    private MutableLiveData<Integer> aTeamScore;
    private MutableLiveData<Integer> bTeamScore;

    private int aBack,bBack;

    private SavedStateHandle handle;

    //这个SavedStateHandle要添加 implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0'
    public MyViewModel(SavedStateHandle handle){
        this.handle = handle;
    }

    public MutableLiveData<Integer> getaTeamScore() {

//        if (aTeamScore == null){
//            aTeamScore = new MutableLiveData<>();
//            aTeamScore.setValue(0);
//        }
//
//        return aTeamScore;

        //handle不用判断空
        if(!handle.contains(MainActivity.KEY_NUMBER_ATEAM)) {
            handle.set(MainActivity.KEY_NUMBER_ATEAM,0);
        }
        return handle.getLiveData(MainActivity.KEY_NUMBER_ATEAM);

    }

    public MutableLiveData<Integer> getbTeamScore() {

//        if (bTeamScore == null){
//            bTeamScore = new MutableLiveData<>();
//            bTeamScore.setValue(0);
//        }
//
//        return bTeamScore;

        if(!handle.contains(MainActivity.KEY_NUMBER_BTEAM)) {
            handle.set(MainActivity.KEY_NUMBER_BTEAM,0);
        }
        return handle.getLiveData(MainActivity.KEY_NUMBER_BTEAM);
    }

    public void aTeamAdd(int p){
//        aBack = aTeamScore.getValue();
//        bBack = bTeamScore.getValue();
//        aTeamScore.setValue(aTeamScore.getValue() + p);


        aBack = getaTeamScore().getValue();
        bBack = getbTeamScore().getValue();
        getaTeamScore().setValue(getaTeamScore().getValue() + p);
    }

    public void bTeamAdd(int p){
//        aBack = aTeamScore.getValue();
//        bBack = bTeamScore.getValue();
//        bTeamScore.setValue(bTeamScore.getValue() + p);

        aBack = getaTeamScore().getValue();
        bBack = getbTeamScore().getValue();
        getbTeamScore().setValue(getbTeamScore().getValue() + p);
    }

    public void reset(){
        aBack = getaTeamScore().getValue();
        bBack = getbTeamScore().getValue();

//        aTeamScore.setValue(0);
//        bTeamScore.setValue(0);

        getaTeamScore().setValue(0);
        getbTeamScore().setValue(0);
    }

    public void undo(){
//        aTeamScore.setValue(aBack);
//        bTeamScore.setValue(bBack);

        getaTeamScore().setValue(aBack);
        getbTeamScore().setValue(bBack);

    }

}
